package com.example.mytayunapi.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UserAgentParser {

    public static String parseUserAgentForBrowser(String userAgent) {
        String browser = "Unknown";
        Pattern pattern = Pattern.compile("(Firefox|MSIE|Chrome|Chromium|Safari|Opera|Edg)\\/([\\d\\.]+)");
        Matcher matcher = pattern.matcher(userAgent);
        if (matcher.find()) {
            browser = matcher.group(1) + " " + matcher.group(2);
        }
        return browser;
    }

    public static String parseUserAgentForOS(String userAgent) {
        String os = "Unknown";
        Pattern pattern = Pattern.compile("(Windows |Linux|macOS|Android|iOS)");
        Matcher matcher = pattern.matcher(userAgent);
        if (matcher.find()) {
            os = matcher.group(1);
        }
        return os;
    }

    public static String parseOSVersionAndArchitecture(String userAgent) {
        String osInfo = "Unknown";
        // 正则表达式匹配操作系统名称、版本和体系结构
        Pattern pattern = Pattern.compile("Windows NT ([\\d\\.]+); Win64; x64");
        Matcher matcher = pattern.matcher(userAgent);

        if (matcher.find()) {
            // 提取版本号并构建操作系统信息字符串
            String version = matcher.group(1);
            osInfo = "Windows " + version + " x64";
        }
        return osInfo;
    }

    public static void main(String[] args) {
        // 示例User-Agent字符串
        String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36";

        // 测试方法
        String browser = parseUserAgentForBrowser(userAgent);
        String os = parseUserAgentForOS(userAgent);
        String osInfo = parseOSVersionAndArchitecture(userAgent);

        // 打印结果
        System.out.println("Browser: " + browser);
        System.out.println("OS: " + os);
        System.out.println("OS Version and Architecture: " + osInfo);
    }
}
